// OldMovie.fx 

// ###################
// ##### GLOBALS #####

uniform float time_cycle_period = 20;
uniform float flicker = 0.4;
uniform float DirtFrequency = 0.0005;
uniform float3 luminance = {0.30, 0.59, 0.11};
uniform float frameJitter = 0.004;
uniform float lumiShift = 0.03;


// #######################
// ##### PARAMENTERS #####
texture noise : Diffuse;
texture Splotches : Diffuse;
texture Sepia : Diffuse;

sampler RT;

sampler Texture2 = sampler_state 
{
    texture = <noise>;
    AddressU  = CLAMP;        
    AddressV  = CLAMP;
    AddressW  = CLAMP;
    MIPFILTER = LINEAR;
    MINFILTER = LINEAR;
    MAGFILTER = LINEAR;
};

sampler SplotchesTx = sampler_state 
{
    texture = <Splotches>;
    AddressU  = CLAMP;        
    AddressV  = CLAMP;
    AddressW  = CLAMP;
    MIPFILTER = LINEAR;
    MINFILTER = LINEAR;
    MAGFILTER = LINEAR;
};

sampler SepiaTx = sampler_state 
{
    texture = <Sepia>;
    AddressU  = CLAMP;        
    AddressV  = CLAMP;
    AddressW  = CLAMP;
    MIPFILTER = LINEAR;
    MINFILTER = LINEAR;
    MAGFILTER = LINEAR;
};


// #######################
// ##### PIXELSHADER #####
float2 calcSpriteAddr(float2 texCoord, float DirtFrequency, float period)
{
   return texCoord + tex1D(Texture2, period  * DirtFrequency);
}

float4 getSplotches(float2 spriteAddr)
{
   // get sprite address into paged texture coords space
   spriteAddr = spriteAddr / 6.3f;
   //spriteAddr = spriteAddr - frac(spriteAddr);
   spriteAddr = spriteAddr - (spriteAddr /33.3f);

   return tex2D(SplotchesTx, spriteAddr);
}

float4 PixelShader(float2 texCoord : TEXCOORD0) : COLOR0
{
	// get sprite address
   float2 spriteAddr = calcSpriteAddr(texCoord, DirtFrequency, time_cycle_period);

    // add some dark and light splotches to the film
   float4 splotches = getSplotches(spriteAddr);
   float4 specs = 1.0f - getSplotches(spriteAddr / 3.0f);

   // convert color to base luminance
   float4 base = tex2D(RT, texCoord + float2(0, spriteAddr.y * frameJitter));
   float lumi = dot(base.rgb, luminance);
   // randomly shift luminance
   lumi -= spriteAddr.x * lumiShift;
   // tone map luminance
   base.rgb = tex1D(SepiaTx, lumi );

   // calc flicker speed
   float darken = frac(flicker * time_cycle_period);

   // we want darken to cycle between 0.6 and 1.0
   darken = abs(darken - 0.5f) * 0.4f + 0.6f;
   // composite dirt onto film
   return base * splotches * darken + specs;
}

technique Glass {
		pass P0{ 
			PixelShader = compile ps_2_0 PixelShader(); 
		}
}